<!--
 * @Author: 李天惊 uf_lee@163.com
 * @Date: 2022-08-15 16:45:26
 * @LastEditors: 李天惊 uf_lee@163.com
 * @LastEditTime: 2023-01-09 10:02:34
 * @FilePath: \grazlink20\uc_sys\src\views\Asset\Quarantine\Index.vue
 * Copyright (c) 2022 by 李天惊 uf_lee@163.com, All Rights Reserved. 
 * 检验检疫记录单
-->
<script setup lang="ts">
import { reactive, PropType, watch, ref, unref } from 'vue'
import { ElButton, ElMessageBox } from 'element-plus'
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { Table } from '@/components/Table'
import See from './components/See.vue'
import Edit from './components/Edit.vue'
import {
  adminFaQuarantineOrderListApi,
  adminFaQuarantineOrderAddApi,
  adminFaQuarantineOrderEditApi,
  adminFaQuarantineOrderDelApi
} from '@/api/fa/quarantine'
import { sysDictRelsApi } from '@/api/dict'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useTable } from '@/hooks/web/useTableTest'
import { useIcon } from '@/hooks/web/useIcon'
// 获取字典
import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
const dict: any = wsCache.get('dict')
// 字典通过value获取label
const getDictLabel = (type, value) => {
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}

const dictRelsData = ref() // 联动数据
const breedSubData = ref([]) // 品种的枚举

const searchRef = ref() // 搜索的标签
const iconSee = useIcon({ icon: 'ep:view' })
const iconEdit = useIcon({ icon: 'ep:edit' })
const iconDel = useIcon({ icon: 'ep:delete' })

const saveLoading = ref(false) //保存中的状态
const editRef = ref<ComponentRef<typeof Edit>>()

const defaultTime = ref<[Date, Date]>([
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 2, 1, 23, 59, 59)
])

// 获取联动关系
const getDictRels = async () => {
  const res = await sysDictRelsApi({
    p_type: 'breed',
    c_type: 'breed_sub'
  })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    dictRelsData.value = res.data
  }
}

// 根据畜别查询品种
const breedGetSub = async (breed_value) => {
  // console.log('breed_value', breed_value, !breed_value)
  if (!breed_value) {
    breedSubData.value = []
  } else {
    let breedData = dictRelsData.value.find((item) => {
      return item.value == breed_value
    })
    breedSubData.value = breedData.children
  }
}

const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<any>>,
    default: () => null
  }
})

const { register, tableObject, methods } = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: adminFaQuarantineOrderListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})
const { getList, setSearchParams } = methods

// 选择畜别的时候触发，处理品种类容
const breedChange = (value) => {
  breedGetSub(value)
  const new_search = unref(searchRef)
  new_search.setData({ ...new_search.getData(), breed_sub: '' })
}

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: '主键',
    fixed: 'left',
    width: 60,
    table: {
      show: true
    },
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'code',
    label: '检验检疫记录单号',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'customer_name',
    label: '牧场名称',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'breed',
    label: '畜别',
    width: 80,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('breed', cellValue)
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dict.breed,
        onChange: breedChange
      },
      show: true
    }
  },
  {
    field: 'breed_sub',
    label: '品种',
    width: 120,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('breed_sub', cellValue)
    },
    search: {
      component: 'Select',
      componentProps: {
        options: breedSubData
      },
      show: true
    }
  },
  {
    field: 'number',
    label: '牲畜数量',
    width: 150,
    search: {
      show: false
    }
  },
  {
    field: 'type',
    label: '类型',
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('quarantine_order_type', cellValue)
    },
    width: 150,
    search: {
      component: 'Select',
      componentProps: {
        options: dict.quarantine_order_type
      },
      show: true
    }
  },
  {
    field: 'creation_time',
    label: '创建时间',
    width: 170,
    form: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        disabled: true,
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    search: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        'is-range': true,
        'unlink-panels': true,
        rangeSeparator: 'To',
        type: 'daterange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        defaultTime: defaultTime
      }
    }
  },
  {
    field: 'creation_user_name',
    label: '创建人',
    width: 80,
    form: {
      show: false
    }
  },
  {
    field: 'quarantine_number',
    label: '检验数量',
    width: 80,
    form: {
      show: false
    }
  },
  {
    field: 'state',
    label: '状态',
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('quarantine_order_state', cellValue)
    },
    width: 150,
    search: {
      component: 'Select',
      componentProps: {
        options: dict.quarantine_order_state
      },
      show: true
    }
  },

  {
    field: 'action',
    width: 150,
    fixed: 'right',
    label: '操作',
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

/****************************** 监听设置固定条件 start ******************************/
const newFixedSearch = ref({})
watch(
  () => props.currentRow,
  (val: any) => {
    if (!val) return
    // 设置固定条件
    newFixedSearch.value = {
      customer_id: val.id
    }
    tableObject.fixedSearch = newFixedSearch.value
  },
  {
    deep: true,
    immediate: true
  }
)
/****************************** 监听设置固定条件 end ******************************/

const apiDel = async (id) => {
  let delRes = await adminFaQuarantineOrderDelApi({ id })
    .catch(() => {})
    .finally(() => {})
  if (delRes) {
    getList()
  }
}

// 处理汇中值
const countData = (data: any) => {
  let number = 0
  let quarantine_number = 0
  let ids: any = []
  for (let i = 0; i < data.detailedData.length; i++) {
    // 判断ids里有没有这个资产
    let isIds = ids.find((item) => {
      return item == data.detailedData[i].earcon_id
    })
    if (!isIds) {
      ids.push(data.detailedData[i].earcon_id)
      number++
      if (data.detailedData[i].state == 2) {
        quarantine_number++
      }
    }
  }
  return { ...data, number, quarantine_number }
}

const dialogVisible = ref(false)

const dialogTitle = ref('')

const actionType = ref('')

const action = async (type: string, row: any = {}) => {
  actionType.value = type
  switch (type) {
    case 'edit':
      dialogTitle.value = '编辑'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'add':
      dialogTitle.value = '新增'
      tableObject.currentRow = {
        is_stop: '0'
      }
      dialogVisible.value = true
      break
    case 'see':
      dialogTitle.value = '查看'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'del':
      ElMessageBox.confirm('确定要删除这个疫苗注射单吗？', '删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          apiDel(row.id)
        })
        .catch(() => {
          console.log('这里是取消confirm弹框')
        })
      break
    default:
      console.log('未知类型')
  }
}

const save = async () => {
  const edit = unref(editRef)
  switch (actionType.value) {
    case 'add':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          // saveLoading.value = true
          const data = (await edit?.getFormData()) as any
          // 改值
          if (data.state == 1) {
            if (data.detailedData.length > 0) {
              if (
                data.detailedData.find((item) => {
                  return item.state == 2
                })
              ) {
                data.state = 2
              }
            }
          }
          // 验证
          if (data.state == 3) {
            if (data.detailedData.length > 0) {
              if (
                data.detailedData.find((item) => {
                  return item.state != 2
                })
              ) {
                ElMessageBox.alert('有未完成的明细，不能完结')
                return false
              }

              if (
                data.detailedData.find((item) => {
                  return item.earcon_id == null
                })
              ) {
                ElMessageBox.alert('明细中打标资产为空，不能完结')
                return false
              }
            } else {
              ElMessageBox.alert('没有明细，不能完结')
              return false
            }
          }
          let res = await adminFaQuarantineOrderAddApi(countData(data))
            .catch(() => {})
            .finally(() => {
              saveLoading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })
      break
    case 'edit':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          // saveLoading.value = true
          const data = (await edit?.getFormData()) as any
          // console.log('edit', data, adminFaQuarantineOrderEditApi)
          // 改值
          if (data.state == 1) {
            if (data.detailedData.length > 0) {
              if (
                data.detailedData.find((item) => {
                  return item.state == 2
                })
              ) {
                data.state = 2
              }
            }
          }
          // 验证
          if (data.state == 3) {
            if (data.detailedData.length > 0) {
              if (
                data.detailedData.find((item) => {
                  return item.state != 2
                })
              ) {
                ElMessageBox.alert('有未完成的明细，不能完结')
                return false
              }

              if (
                data.detailedData.find((item) => {
                  return item.earcon_id == null
                })
              ) {
                ElMessageBox.alert('明细中打标资产为空，不能完结')
                return false
              }
            } else {
              ElMessageBox.alert('没有明细，不能完结')
              return false
            }
          }
          let res = await adminFaQuarantineOrderEditApi(countData(data))
            .catch(() => {})
            .finally(() => {
              saveLoading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })
      break
    default:
      console.log('未知类型')
  }
}

/****************************** 初始化 start ******************************/
const init = async () => {
  // 列表查询
  await getList()
  // 获取关联关系
  await getDictRels()
}
init()
/****************************** 初始化 end ******************************/
</script>

<template>
  <ContentWrap>
    <Search
      ref="searchRef"
      :schema="allSchemas.searchSchema"
      @search="setSearchParams"
      @reset="setSearchParams"
    />

    <div class="mb-10px">
      <ElButton type="primary" @click="action('add')">新增</ElButton>
    </div>

    <Table
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :border="true"
      :pagination="{
        total: tableObject.count
      }"
      @register="register"
      :selection="false"
    >
      <template #action="{ row }">
        <ElButton circle :icon="iconSee" @click="action('see', row)" title="查看" />
        <ElButton
          v-if="row.state != 3"
          circle
          :icon="iconEdit"
          @click="action('edit', row)"
          title="编辑"
        />
        <ElButton
          v-if="row.state != 3"
          circle
          :icon="iconDel"
          @click="action('del', row)"
          title="删除"
        />
        <!-- <ElButton circle :icon="iconAssets" @click="action('assets', row)" title="打标资产" /> -->
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Edit v-if="actionType == 'edit'" ref="editRef" :id="tableObject.currentRow.id" />

    <Edit v-if="actionType == 'add'" ref="editRef" />

    <See v-if="actionType == 'see'" :id="tableObject.currentRow.id" />

    <!-- <Assets
      v-if="actionType == 'assets'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
    /> -->

    <template #footer>
      <ElButton
        v-if="actionType == 'add' || actionType == 'edit'"
        type="primary"
        :loading="saveLoading"
        @click="save()"
      >
        保存
      </ElButton>
      <ElButton @click="dialogVisible = false">关闭</ElButton>
    </template>
  </Dialog>
</template>
